from blueprints import post_blueprint
from models import Blog, UpdateInstance, QueryOneInstance, NowStr, Check, DeleteInstance, Like
from tools.decorate import pack_session
from tools.response import ResponsePostJson, Response


# 修改未审核或者发布新的帖子
@post_blueprint.route('/my/service/publish_blog', methods=['POST'])
@pack_session
def post_my_service_of_publish_blog(data):
    def cb(json):
        blog=None
        if json['id']:
            blog=QueryOneInstance(Blog,{'id':json['id']})
        else:
            blog = Blog(uid=data['session']['uid'])
        blog.published=True
        blog.time = NowStr()
        UpdateInstance(blog,json)

        check = Check(uid=data['session']['uid'],pid=blog.id)
        UpdateInstance(check)

        return Response("发布成功,待审核")
    return ResponsePostJson(['title','sort','content'],cb,['id'])

@post_blueprint.route('/anyone/service/unpass/blog/<int:pid>', methods=['POST'])
@pack_session
def post_anyone_service_of_unpass_blog(data):
    def cb(json):
        blog=QueryOneInstance(Blog,{'id':data['route']['pid']})
        blog.checked=True
        blog.passed=False
        UpdateInstance(blog,json)

        check = QueryOneInstance(Check,{'pid':blog.id})
        DeleteInstance(check)
        return Response("成功设置未通过")
    return ResponsePostJson(['reason'],cb)

@post_blueprint.route('/anyone/service/pass/blog/<int:pid>', methods=['POST'])
@pack_session
def post_anyone_service_of_pass_blog(data):
    def cb(json):
        blog=QueryOneInstance(Blog,{'id':data['route']['pid']})
        blog.checked=True
        blog.passed=True
        UpdateInstance(blog,json)

        check = QueryOneInstance(Check,{'pid':blog.id})
        DeleteInstance(check)
        return Response("成功设置通过")
    return ResponsePostJson([],cb)

#被举报了
@post_blueprint.route('/anyone/service/recheck/blog/<int:pid>', methods=['POST'])
@pack_session
def post_anyone_service_of_recheck_blog(data):
    def cb(json):
        check = Check(pid=data['route']['pid'],uid=data['session']['uid'])
        UpdateInstance(check)
        return Response("已提交举报，待审核")
    return ResponsePostJson([],cb)

@post_blueprint.route('/anyone/service/like/blog/<int:pid>', methods=['POST'])
@pack_session
def post_anyone_service_of_like_blog(data):
    def cb(json):
        like = QueryOneInstance(Like,{'uid':data['session']['uid'],'pid':data['route']['pid']})
        if not like:
            like = Like(uid=data['session']['uid'],pid=data['route']['pid'])
        like.time = NowStr()
        UpdateInstance(like)
        return Response("已喜欢")
    return ResponsePostJson([],cb)

@post_blueprint.route('/anyone/service/unlike/blog/<int:pid>', methods=['POST'])
@pack_session
def post_anyone_service_of_unlike_blog(data):
    like = QueryOneInstance(Like,{'pid':data['route']['pid'],'uid':data['session']['uid']})
    DeleteInstance(like)
    return Response("成功取消喜欢")
